package com.google.code.p.restrpc.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.p.restrpc.RpcOptions;

/**
 * @author dz
 */
public final class RpcOptionsFactory {
    
    private static final Log logger = LogFactory.getLog(RpcOptionsFactory.class);
    
    private static RpcOptions _instance;
    
    /**
     * @param instance
     */
    public static void setClientSettings(RpcOptions instance) {
        _instance = instance;
    }
    
    /**
     * @param properties
     * @return
     */
    public static RpcOptions getInstance(Properties properties) {
        return new DefaultRpcOptions(properties);
    }
    
    /**
     * return the default and global options of RestRpc
     * 
     * @return
     */
    public static RpcOptions getInstance() {
        if (_instance != null) {
            return _instance;
        }
        return ClientSettingsHolder.instance;
    }
    
    private static class ClientSettingsHolder {
        
        static RpcOptions instance = newRpcOptions();
        
        private static RpcOptions newRpcOptions() {
            InputStream is = RpcOptionsFactory.class.getResourceAsStream("/restrpc.client.properties");
            if (is == null) {
                logger.debug("The restrpc.client.properties not found! All options goes to default value!");
                return new DefaultRpcOptions();
            }
            try {
                Properties properties = new Properties();
                properties.load(is);
                return new DefaultRpcOptions(properties);
            }
            catch (IOException e) {
                throw new RpcClientConfigurationException("Loading restrpc.client.properties failed!",
                                                              e);
            }
        }
        
    }
    
}
